import json
import os
import time

from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from home.models import Area, Facility, HouseImage
from fdfs_client.client import Fdfs_client
from home.models import House
from ihome.utils.mixins import LoginRequiredMixin

from order.models import Order

'''查看我的房屋列表 /api/v1.0/user/houses'''


class HousesMessageView(View):
    def post(self, request):
        # /api/v1.0/houses
        req_data = json.loads(request.body.decode())
        # 数据验证
        try:
            title = req_data.get('title')
            price = req_data.get('price')
            area_id = int(req_data.get('area_id'))
            address = req_data.get('address')
            room_count = int(req_data.get('room_count'))
            acreage = int(req_data.get('acreage'))
            unit = req_data.get('unit')
            capacity = int(req_data.get('capacity'))
            beds = req_data.get('beds')
            deposit = req_data.get('deposit')
            min_days = int(req_data.get('min_days'))
            max_days = int(req_data.get('max_days'))
            facility = list(req_data.get('facility'))
        except Exception as e:
            return JsonResponse({
                'errmsg': '数据类型有误',
                'errno': 400,
            })
        if not all([title, price, area_id, address, room_count,
                    acreage, unit, capacity, beds, deposit,
                    min_days, facility]):
            return JsonResponse({
                "errno": 400,
                "errmsg": "缺少必传参数",
            })
        # 地址是否存在
        try:
            city = Area.objects.get(id=area_id)
        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "城区id不存在",
            })

        if min_days and max_days < 0:
            return JsonResponse({
                "errno": 400,
                "errmsg": "入住天数填写有误",
            })
        try:
            for facility_id in facility:
                city = Facility.objects.get(id=facility_id)

        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "设施信息不存在",
            })

        house = House.objects.create(title=title, price=price, area_id=area_id, address=address,
                                     room_count=room_count, acreage=acreage, unit=unit, capacity=capacity,
                                     beds=beds, deposit=deposit, min_days=min_days, max_days=max_days,
                                     user_id=request.user.id)

        try:
            for facility_id in facility:
                house.facility.add(facility_id)
        except Exception as e:
            print(e)
            return JsonResponse({
                "errno": 400,
                "errmsg": "数据库添加失败",
            })

        else:
            return JsonResponse({
                "errno": "0",
                "errmsg": "发布成功",
                "data": {
                    "house_id": house.id
                }
            })

    def get(self, request):
        aid = request.GET.get('aid')
        print(aid)
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        page = request.GET.get('p', 1)
        sehome_li = []
        nginx_url = 'http://192.168.19.131:8888/'
        try:
            orders = Order.objects.all()
            order_id_li = []
            for order in orders:
                start_date1 = order.begin_date
                end_date1 = order.end_date
                # 判断房子在日期内有没有被人预定
                start_date1 = str(start_date1)
                end_date1 = str(end_date1)
                sd = time.mktime(time.strptime(start_day, '%Y-%m-%d'))
                ed = time.mktime(time.strptime(end_day, '%Y-%m-%d'))
                sd1 = time.mktime(time.strptime(start_date1, '%Y-%m-%d'))
                ed1 = time.mktime(time.strptime(end_date1, '%Y-%m-%d'))
                if sd1 <= sd <= ed1 or sd1 <= ed <= ed1 or sd < sd1 < ed or sd < ed1 < ed:
                    if order.status < 3:
                        # 将不可以租到的house_id存入列表(订单状态在待评价之前的都应该保存)
                        order_id_li.append(order.house_id)
        # 根据区域id取到该城区里的所有房屋对象
        except:
            return JsonResponse({
                'msm': '数据库查询失败'
            })

        if sort_key == 'new':
            sort = '-'
        else:
            sort = ''
        try:
            houses = House.objects.exclude(id__in=order_id_li).order_by(sort + 'order_count')
            paginator = Paginator(houses, 3)
            results = paginator.get_page(page)

            for i in results:
                if i.area_id == int(aid):
                    sehome_li.append({
                        "address": i.address,
                        "area_name": i.area.name,
                        "ctime": i.create_time,
                        "house_id": i.id,
                        "img_url": nginx_url + i.index_image_url,
                        "order_count": i.order_count,
                        "price": i.price,
                        "room_count": i.room_count,
                        "title": i.title,
                        "user_avatar": nginx_url + i.user.avatar.name
                    })
        except Exception as e:

            return JsonResponse({
                "errmsg": "传入城区ID有误",
                "errno": "400"
            })
        return JsonResponse({
            "data": {
                "houses": sehome_li,
                "total_page": paginator.num_pages,
            },
            "errmsg": "请求成功",
            "errno": "0"
        })


class HouseImageView(View):
    # /api/v1.0/houses/[int:house_id]/images
    def post(self, request, house_id):
        nginx_url = 'http://192.168.19.131:8888/'
        pic = request.FILES.get('house_image')
        pic = pic.read()
        client = Fdfs_client(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'utils/fastdfs/client.conf'))
        try:
            ret = client.upload_by_buffer(pic)['Remote file_id']
            HouseImage.objects.create(url=ret, house_id=house_id)

            house = House.objects.get(id=house_id)
            image = house.index_image_url
            if not image:
                House.objects.filter(id=house_id).update(index_image_url=ret)
        except Exception as e:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片上传失败"
            })
        return JsonResponse({
            "data": {
                "url": nginx_url + ret
            },
            "errno": 0,
            "errmsg": "图片上传成功"
        })


class UserHouses(LoginRequiredMixin,View):
    """查看我的房源"""
    def get(self, request):
        """默认图片地址首部"""
        nginx_url = 'http://192.168.19.131:8888/'
        try:
            '''提取出数据库，获取用户为1的房屋信息'''
            houses_message = House.objects.filter(user_id=request.user.id)
            houses_list = []
            '''遍历该用户所有的房屋信息，并且返回'''
            for home in houses_message:
                '''关联查询'''
                area = home.area
                user_avatar = home.user.avatar
                houses_list.append({
                    "address": home.address,
                    "area_name": area.name,
                    "ctime": area.create_time,
                    "house_id": home.id,
                    "img_url": nginx_url + home.index_image_url,
                    "order_count": home.order_count,
                    "price": home.price,
                    "room_count": home.room_count,
                    "title": home.title,
                    "user_avatar": nginx_url+user_avatar.name
                })
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '获取数据库失败'
            })
        return JsonResponse({
            'data': {
                'houses': houses_list
            },
            'errmsg': 'ok',
            'errno': '0'
        })


class HousesIndex(View):
    """首页房屋推荐 api/v1.0/houses/index/"""
    def get(self, request):
        nginx_url = 'http://192.168.19.131:8888/'
        try:
            '''提取所有房屋信息'''
            houses_message = House.objects.all()
            '''仅获取前五个信息'''
            houses_message = houses_message[:5]
            houses_list = []
            for home in houses_message:
                houses_list.append(
                    {
                        "house_id": home.id,
                        "img_url": nginx_url + home.index_image_url,
                        "title": home.title,
                    },
                )
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '获取数据库失败'
            })
        return JsonResponse({
            'data': houses_list,
            'errmsg': 'ok',
            'errno': '0'
        })
class HousesParticularsView(View):
    def get(self,request,house_id):
        nginx_url = 'http://192.168.19.131:8888/'
        if not request.user.id:
            request.user.id = -1
        id = request.user.id
        try:
            house = House.objects.get(id=house_id)
            order = Order.objects.filter(house_id=house_id)
            img = HouseImage.objects.filter(house_id=house_id)
            facility_li = []
            comment_li = []
            houseimg_li = []
            img_li = []
            # 循环遍历出所有该房屋的订单信息
            for data in order:
                comment_li.append({
                    "comment": data.comment,
                    "ctime": data.update_time,
                    "user_name": data.user.username
                })
            #  循环遍历出该房屋所有的设施ID
            for data in house.facility.all():
                facility_li.append(data.id)
            # 遍历出该房屋所有图片
            for data in img:
                img_li.append(nginx_url + data.url)
            house = {
                        "acreage": house.acreage,
                        "address": house.address,
                        "beds": house.beds,
                        "capacity": house.capacity,
                        "comments": comment_li,
                        "deposit": house.deposit,
                        "facilities": facility_li,
                        "hid": house.id,
                        "img_urls": img_li,
                        "max_days": house.max_days,
                        "min_days": house.min_days,
                        "price": house.price,
                        "room_count": house.room_count,
                        "title": house.title,
                        "unit": house.unit,
                        "user_avatar": nginx_url + house.user.avatar.name,
                        "user_id": house.user.id,
                        "user_name": house.user.real_name
                    }
            return JsonResponse({
                "data": {
                    "house": house,
                    "user_id": id
                },
                "errmsg": "OK",
                "errno": "0"
            })

        except:
            return JsonResponse({
                "errmsg": "数据库操作失败",
                "errno": "400"
            })
